package reauthorize

import (
	"time"
	"errors"
	"github.com/dgrijalva/jwt-go"
	"github.com/astaxie/beego"
)

type User struct {
	PartnerId   int64                 `json:"partner_id"`
	MemberId    int64                 `json:"member_id"`
	Scenes      string                `json:"scenes"`
	//LastName    string              `json:"last_name"`
	//Email       string              `json:"email"`
	//Username    string              `json:"username"`
	//Permissions map[string][]string `json:"permissions"`
}

type claims struct {
	User User `json:"user"`
	jwt.StandardClaims
}

type Signer struct {
	jwtIssuer  string
	jwtExpiry  int64
	privateKey string
}

func NewSigner(jwtIssuer string, jwtExpiry int64, privateKey string) (*Signer) {
	signer := &Signer{
		jwtIssuer:  jwtIssuer,
		jwtExpiry:  jwtExpiry,
		privateKey: privateKey,
	}
	return signer
}

// Sign is used to create a signed token
func (signer *Signer) Sign(user User) (string, error) {
	token := jwt.New(jwt.GetSigningMethod("HS256"))
	claims := token.Claims.(jwt.MapClaims)
	claims["User"] = struct {
		PartnerId int64
		MemberId  int64
		Scenes    string
	}{PartnerId:user.PartnerId,MemberId:user.MemberId}
	claims["exp"] = time.Now().UTC().Add(time.Second*100).Unix()
	tokenSecret := beego.AppConfig.String("RpcSecret")
	return token.SignedString([]byte(tokenSecret))
}


func CheckSign(tokenStr string) error {
	tokenSecret := beego.AppConfig.String("RpcSecret")
	token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
		return []byte(tokenSecret), nil
	})
	if token.Valid {
		return nil
	} else if ve, ok := err.(*jwt.ValidationError); ok {
		if ve.Errors&jwt.ValidationErrorMalformed != 0 {
			return errors.New("That's not even a token")
		} else if ve.Errors&(jwt.ValidationErrorExpired|jwt.ValidationErrorNotValidYet) != 0 {
			return errors.New("Token is either expired or not active yet")
		} else {
			return errors.New("Couldn't handle this token")
		}
	} else {
		return errors.New("Couldn't handle this token")
	}
}
